package com.xu.commons.dao;

import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class DefaultDataAccessor {
	
	private static final Logger logger = LoggerFactory.getLogger(DefaultDataAccessor.class);
	
	private final QueryRunner queryRunner;
	 public DefaultDataAccessor() {
	        DataSource dataSource = DatabaseHelper.getDataSource();
	        queryRunner = new QueryRunner(dataSource);
	    }
	 public  <T> T queryEntity(Class<T> entityClass,String sql,Object ...params){
		 T result;
		try {
			result = queryRunner.query(sql, new BeanHandler<T>(entityClass), params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			logger.error("查询出错");
		    	e.printStackTrace();
			 throw new RuntimeException(e);
		}
		return result;
	 }
	 
	 public  <T> List<T> queryEntityList(Class<T> entityClass,String sql,Object ...params){
		 List<T> result;
		 try {
			result = queryRunner.query(sql, new BeanListHandler<T>(entityClass), params);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("查询出错");
			 throw new RuntimeException(e);
		}
		 return result;
	 }
	  private static void printSQL(String sql) {
	        logger.debug("[Smart] SQL - {}", sql);
	    }
}
